<!--
  -- 描述：字典下拉树列表，可以用v-model双向绑定
  --
  -- 作者：cyq
  -- 时间：2018/9/1 12:45
-->
<template>
  <el-popover
    placement="bottom-start"
    trigger="click"
    v-model="opened">
    <el-tree ref="tree" node-key="id" :data="list" :props="{label: 'text', children: 'children'}"
             @node-click="selectHandler">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>&nbsp;<span class="text-danger">{{ data.available===0?'[禁用]':'' }}</span>
      </span>
    </el-tree>
    <el-input
      slot="reference"
      placeholder="选择上级字典"
      suffix-icon="el-icon-arrow-down"
      :value="text"
      :readonly="true">
    </el-input>
  </el-popover>
</template>

<script>
  export default {
    name: "DictionarySelect",
    model: {
      prop: 'mval',
      event: 'modelValue'
    },
    props: ['mval', 'parentCode'],
    watch: {
      mval: {
        handler() {
          this.defaultCheck();
        },
        deep: true
      }
    },
    mounted: function() {
      this.api.post('/bucket-system/system/dict/all', {code: this.parentCode})
        .then((data) => {
          let _d = {id:'', text:'根字典', children:data.data};
          this.list = [_d];
          // this.list = data.data;
        });
    },
    updated: function(){
      this.defaultCheck();
    },
    data() {
      return {
        list: [],
        opened: false,
        text: ''
      }
    },
    methods: {
      defaultCheck() {
        if(this.mval){
          this.$refs.tree.setCurrentKey(this.mval);
          this.text = this.$refs.tree.getCurrentNode().text
        }else {
          this.$refs.tree.setCurrentKey(null);
          this.text = '';
        }
      },
      inputHandler: function(val){
        this.$emit('modelValue', val)
      },
      selectHandler: function(obj, node, tree){
        this.text = obj.text;
        this.inputHandler(obj.id);
        this.opened = false;
      }
    }
  }
</script>
